package com.bugbuff.dubbo.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bugbuff.common.mapper.UserInfoMapper;
import com.bugbuff.common.mapper.UserMapper;
import com.bugbuff.common.pojo.PageResult;
import com.bugbuff.common.pojo.User;
import com.bugbuff.common.pojo.UserInfo;
import com.bugbuff.dubbo.server.api.LogsApi;
import com.bugbuff.dubbo.server.api.UserLikeApi;
import com.bugbuff.dubbo.server.api.UserManageApi;
import com.bugbuff.dubbo.server.pojo.FrozenUser;
import com.bugbuff.dubbo.server.pojo.Logs;
import com.bugbuff.dubbo.server.vo.UserManageInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class UserManageService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Reference
    private UserManageApi userManageApi;

    @Reference
    private LogsApi logsApi;

    @Reference
    private UserLikeApi userLikeApi;

    /**
     * 根据userID查询userInfo封装到UserManageInfoVo中
     *
     * @param userID
     * @return
     */
    public UserManageInfoVo findUserInfo(Long userID) {

//        将UserInfo的信息封装到UserManageInfoVo中
        UserManageInfoVo userManageInfoVo = new UserManageInfoVo();
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userID);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        fillUserInfoToVo(userInfo, userManageInfoVo);

//        封装手机号
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, userID);
        User user = userMapper.selectOne(wrapper);
        userManageInfoVo.setMobile(user.getMobile());

//        封装个性签名
        userManageInfoVo.setPersonalSignature(getPersonalSignature(userID));

//        封装喜欢、被喜欢、配对人数
        userManageInfoVo.setCountBeLiked(userLikeApi.queryFansList(userID).size());
        userManageInfoVo.setCountLiked(userLikeApi.queryLikeList(userID).size());
        userManageInfoVo.setCountMatching(userLikeApi.queryMutualLikeList(userLikeApi.queryLikeList(userID), userID).size());


        return userManageInfoVo;
    }

    /**
     * 为个性签名添加假数据
     *
     * @param userID
     * @return
     */
    private String getPersonalSignature(Long userID) {
        Random r = new Random();
        List<String> list = new ArrayList<>();
        list.add("前面的路布满荆棘，我有过迟疑，却从未后退。");
        list.add("告诉自己：想不开就不想，得不到就不要。");
        list.add("生活其实很简单，过了今天就是明天。");
        list.add("低头哭过别忘了抬头继续走。");
        list.add("摆正姿态，收起你毫无价值的无病呻吟。");
        list.add("自己做出决定，才是精彩的人生。");
        list.add("有种脾气叫，不放弃。");
        list.add("活着不是靠泪水博得同情，而是靠汗水赢得掌声。");
        list.add("我相信，路总会有平坦的一面。");
        list.add("你既然认准一条道路，何必去打听要走多久！");

        if (userID <= 10L) {
            return list.get(Convert.toInt(userID) - 1);
        } else {
            return list.get(r.nextInt(list.size() - 1));
        }
    }

    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param userManageInfoVo
     */
    private void fillUserInfoToVo(UserInfo userInfo, UserManageInfoVo userManageInfoVo) {
        BeanUtil.copyProperties(userInfo, userManageInfoVo, "id", "sex");
        userManageInfoVo.setSex(userInfo.getSex().toString());
        userManageInfoVo.setUserStatus(userManageApi.findUserStatus(userInfo.getUserId()));

//        封装最近登录时间和最近登陆地点
        Logs logs = logsApi.queryLogs(userInfo.getUserId());
        if (ObjectUtil.isNotEmpty(logs)) {
            userManageInfoVo.setLastActiveTime(logs.getLoginTime());
            userManageInfoVo.setLastLoginLocation(logs.getLandingLocation());
        }
    }

    /**
     * 查询用户基本数据，同时进行分页操作
     *
     * @param page
     * @param pagesize
     * @param id
     * @return
     */
    public PageResult findUserInfoByPage(Integer page, Integer pagesize, Long id, String nickname, String city) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);

//        查询数据库并分页
        IPage<UserInfo> iPage = new Page(page, pagesize);

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(id))
            queryWrapper.like("id", id);
        if (StringUtils.isNotEmpty(nickname))
            queryWrapper.like("nick_name", nickname);
        if (StringUtils.isNotEmpty(city))
            queryWrapper.like("city", city);

        userInfoMapper.selectPage(iPage, queryWrapper);
        List<UserInfo> list = iPage.getRecords();
        pageResult.setCounts(Convert.toInt(iPage.getTotal()));
        pageResult.setPages(Convert.toInt(iPage.getPages()));

        List<UserManageInfoVo> voList = new ArrayList<>();
        for (UserInfo userInfo : list) {
            UserManageInfoVo userManageInfoVo = new UserManageInfoVo();
            fillUserInfoToVo(userInfo, userManageInfoVo);
            voList.add(userManageInfoVo);
        }

        pageResult.setItems(voList);

        return pageResult;
    }

    /**
     * 冻结用户操作
     *
     * @param frozenUser
     * @return
     */
    public Boolean freezeUser(FrozenUser frozenUser) {
        frozenUser.setId(ObjectId.get());
        frozenUser.setUserStatus("2");
        frozenUser.setReasonsForThawing("无");
        frozenUser.setCreated(System.currentTimeMillis());
        return userManageApi.freezeUser(frozenUser);
    }

    /**
     * 解冻用户操作
     *
     * @param frozenUser
     * @return
     */
    public Boolean unfreezeUser(FrozenUser frozenUser) {
        frozenUser.setUserStatus("1");
        return userManageApi.unfreezeUser(frozenUser);
    }
}
